<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
        <!-- 警告区域 -->
        <el-alert
            title="注意：只允许为第三级参数设置相关参数"
            type="warning"
            show-icon>
        </el-alert>
        <!-- 选择商品参数区域 -->
        <el-row class="cat_opt">
            <el-col>
                <span>选择商品参数：</span>
                <!-- 选择商品参数的级联 -->
                <el-cascader
                            v-model="selctedKeys"
                            :options="cateList"
                            :props="{ expandTrigger: 'hover',...cascaderProps }"
                            @change="getParamsList"
                            ></el-cascader>
            </el-col>
            
        </el-row>
        
        <!-- tab页签区域 -->
        <el-tabs v-model="activeName" @tab-click="getParamsList">
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" :disabled="selctedKeys.length!==3" @click="addDialogVisible=true">添加参数</el-button>
                <el-table :data="tabForms" style="width: 100%" stripe border>
                    <el-table-column type="expand">
                        <template v-slot="scope">
                            
                            <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">{{item}}</el-tag>
                            <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                >
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            
                        </template>
                    </el-table-column>
                    <el-table-column type="index" label="#"></el-table-column>
                    <el-table-column
                        prop="attr_name"
                        label="参数名称"
                        >
                    </el-table-column>
                    <el-table-column label="操作">
                        <template v-slot="scope">
                            <el-button size="mini" type="primary" icon="el-icon-edit"  @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteDialog(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only">
                <!-- 添加静态属性的按钮 -->
                <el-button type="primary" :disabled="selctedKeys.length!==3" @click="addDialogVisible=true">添加属性</el-button>
                <el-table :data="tabForms" stripe border>
                    <el-table-column type="expand">
                        <template v-slot="scope">
                            
                            <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">{{item}}</el-tag>
                            <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                >
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            
                        </template>
                    </el-table-column>
                    <el-table-column type="index" label="#"></el-table-column>
                    <el-table-column prop="attr_name" label="属性名称"></el-table-column>
                    <el-table-column label="操作">
                        <template v-slot="scope">
                            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteDialog(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
        :title="'添加'+titleTex"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
        >
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
            <el-form-item :label="titleTex" prop="attr_name">
                <el-input v-model="addForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addNewParams">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog
        :title="'修改'+titleTex"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
        >
        <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="100px">
            <el-form-item :label="titleTex" prop="attr_name">
                <el-input v-model="editForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
name:'Params',
data() {
    return {
        cateList:[],
        cascaderProps:{
            value:'cat_id',
            label:'cat_name',
            children:'children',
            
        },
        // 级联选择框选中的函数
        selctedKeys:[],
        activeName:'many',
        // tab标签的表格数据
        tabForms:[],
        // 添加表格能否可视
        addDialogVisible:false,
        // 添加表单参数数据对象
        addForm:{
            attr_name:'',
            
        },
        // 表单验证规则
        addFormRules:{
            attr_name:[
                { required: true, message: '请输入参数名称', trigger: 'blur' },

            ]
        },
        editDialogVisible:false,
        editForm:{}

    }
},
created() {
    this.getCateList()
},
methods: {
    async getCateList() {
        const {data:res}=await this.$http.get('categories')
        if(res.meta.status!==200) return this.$message.error(res.meta.msg)
        this.cateList=res.data
        // console.log(this.cateList);
    },
    // 获取参数列表
    async getParamsList() {
        if(this.selctedKeys.length!==3) {
            this.selctedKeys=[],
            this.tabForms=[]
            return
        }
        // console.log(this.selctedKeys);
        const {data:res}=await this.$http.get('categories/'+this.cateId+'/attributes',{params:{sel:this.activeName}})
        if(res.meta.status!==200) return this.$message.error(res.meta.msg)
        res.data.forEach(element => {
            element.attr_vals=element.attr_vals?element.attr_vals.split(' '):[]
            this.$set(element, "inputValue", "");
            this.$set(element, "inputVisible",false);
        });
        this.tabForms=res.data
        // console.log(this.tabForms);
    },
    addDialogClosed() {
        this.$refs.addFormRef.resetFields()
    },
    addNewParams() {
        this.$refs.addFormRef.validate(async valid=>{
            if(!valid) return
            // 可以发起添加参数的网络请求
            const {data:res}=await this.$http.post('categories/'+this.cateId+'/attributes',{
                attr_name:this.addForm.attr_name,
                attr_sel:this.activeName
            })
            // console.log(res);
            if(res.meta.status!==201) return this.$message.error('添加参数失败')
            this.$message.success('添加参数成功')
            this.addDialogVisible = false
            // 重新获取参数列表
            this.getParamsList()
        })
    },
    async showEditDialog(id) {
        this.editDialogVisible=true
        // console.log(id);
        const {data:res}=await this.$http.get('categories/'+this.cateId+'/attributes/'+id,{
            params:{attr_sel:this.activeName}
        })
        // console.log(res);
        if(res.meta.status!==200) return this.$message.error('查询参数信息失败')
        this.editForm=res.data
    },
    editDialogClosed() {
        this.$refs.editFormRef.resetFields()
    },
    editParams() {
        this.$refs.editFormRef.validate(async valid=>{
        if(!valid) return
        const {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{
            attr_name:this.editForm.attr_name,
            attr_sel:this.activeName
        })
        // console.log(res);
        if(res.meta.status!==200) return this.$message.error('修改参数信息失败')
        this.$message.success('修改参数信息成功')
        this.editDialogVisible = false
        // console.log(res);
        this.getParamsList()
        })
    },
    async deleteDialog(id) {
        const comfirmResult=await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        // 确认删除confirm
        // 取消删除concel
        // console.log(comfirmResult);
        if(comfirmResult!=='confirm') {
            return this.$message.info('取消了删除')
        }
        const {data:res}=await this.$http.delete('categories/'+this.cateId+'/attributes/'+id)
        if(res.meta.status!==200) return this.$message.error('删除参数失败')
        this.$message.success('删除参数成功')
        this.getParamsList()
    },
    handleInputConfirm(row) {
        // 输入空字符
        if(row.inputValue.trim().length===0) {
            row.inputVisible = false;
            row.inputValue = '';
            return
        }
        row.attr_vals.push(row.inputValue.trim())
        row.inputVisible = false;
        row.inputValue = '';
        // 需要发送请求 把数据存到数据库中
        this.saveAttrValues(row,'添加')

    },
    async saveAttrValues(row,str) {
        const {data:res}=await this.$http.put('categories/'+this.cateId+'/attributes/'+row.attr_id,{
            attr_name:row.attr_name,
            attr_sel:row.attr_sel,
            attr_vals:row.attr_vals.join(' ')

        })
        if(res.meta.status!==200) return this.$message.error(str+'参数失败')
        this.$message.success(str+'参数成功')
    },
    showInput(row) {
        row.inputVisible = true;
        // 让文本框自动获得焦点
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    handleClose(i,row) {
        row.attr_vals.splice(i,1)
        this.saveAttrValues(row,'删除')
    }
    
},
computed:{
    cateId() {
        if(this.selctedKeys.length===3) {
            return this.selctedKeys[2]
        }
    },
    titleTex() {
        return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
}
}
</script>

<style scoped>
.cat_opt {
    margin-top: 15px;
}
.el-tag {
    margin: 5px;
}
.input-new-tag {
    width: 100px;
    margin-left: 15px;
}
</style>